<?php

namespace App\Admin\Actions\OrderAction;

use App\Models\Order;
use App\Models\Reward;
use Illuminate\Http\Request;
use App\Services\CancelProductOrder\CancelProductOrder;
use Encore\Admin\Actions\RowAction;

class OrderCancel extends RowAction
{
    public $name = '取消';
    
    public function handle(Order $model, Request $request)
    {

    	$money = big_decimal((string)$request->get('money', 0));

	    if ($model->isClosed()) {
		    return $this->response()->error('目标订单已关闭');
	    } elseif (!$model->isPaid()) {
		    return $this->response()->error('目标订单未支付');
	    } elseif ($model->cancelled_at) {
		    return $this->response()->error('目标订单已取消');
	    }elseif (!$money->isLessThanOrEqualTo($model->total_amount)) {
		    return $this->response()->error('退款金额超过目标订单付款金额');
	    }
    	$reward =Reward::query()->where('order_id',$model->id)->first();
    	if(!empty($reward) && $reward->is_settle){

    		 return $this->response()->error('该订单已结算佣金，不可退回');
    	}

	    app(CancelProductOrder::class, [
	    	'order' => $model,
	    	'money' => (string)$request->get('money', 0)
	    ])->cancel();
	    
	    return $this->response()->success('订单取消已提交')->refresh();
    }
	
	public function form()
	{
		$this->text('money', '退款金额')
			->rules('required|numeric|min:0.01');
	}
}
